// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package register

import (
	"context"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/guest"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
)

// Logic
// 注册账号.
type Logic struct {
	request *Request

	oauth             *models.Oauth
	oauthService      *services.OauthService
	user              *models.Users
	userService       *services.UsersService
	userMobile        *models.UserMobiles
	userMobileService *services.UserMobilesService
	userStaticService *services.UserStatisticService

	guest.Login
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request: &Request{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	err = validator.Json(i, o.request)
	return
}

// Run
// 注册过程.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err     error
		has     bool
		logined *guest.Logined
		res     = result.New()
		sess    *db.Session
	)

	// 1. 建立连接.
	//    触发事务模式.
	if sess, err = db.Config.GetMaster(ctx); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 查询授权.
	o.oauthService = services.NewOauthService(sess)

	// 2.1 查询过程.
	if o.oauth, has, err = o.oauthService.Dao.GetById(ctx, o.request.AuthId); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2.2 授权检查.
	if !has || o.oauth.UserCode != o.request.UserCode {
		return res.WithError(errs.ErrUserOauthNotFound)
	}

	// 2.3 直接登录.
	//     一般出现在2台+设备同时处在提交注册页面, 不同顺序提交注册时触发.
	if o.oauth.UserId.IsBound() {
		// 登录过程.
		if logined, err = o.InitLoginedForUser(ctx, o.oauth, o.request.Device); err != nil {
			return res.WithError(err)
		}

		// 登录成功.
		return res.With(logined)
	}

	// 3. 手机校验.
	//    用户必须在注册页面通过Code到微信, 抖音获取手机号. 获取到手机号时立即保存到授权
	//    记录中.
	if o.oauth.OpenMobile.IsUnspecified() {
		return res.WithError(errs.ErrUserMobileNotBind)
	}

	// 3.1 准备校验.
	o.userMobileService = services.NewUserMobilesService(sess)

	// 3.2 查询手机.
	if o.userMobile, has, err = o.userMobileService.Dao.GetBy(ctx, "mobile", o.oauth.OpenMobile); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 3.3 直接登录.
	//     复用其它授权的账号, 保证同一个手机在不同的小程序(微信、抖音)绑定到同一个账号上.
	if has && o.userMobile.UserId.IsBound() {
		o.oauth.UserId = o.userMobile.UserId

		// 保存关系.
		if _, err = o.oauthService.Dao.UpdateFieldsById(ctx, map[string]any{
			"user_id": o.oauth.UserId,
		}, o.oauth.Id); err != nil {
			return res.WithError(errs.ErrDatabaseQuery)
		}

		// 登录过程.
		if logined, err = o.InitLoginedForUser(ctx, o.oauth, o.request.Device); err != nil {
			return res.WithError(err)
		}

		// 登录成功.
		return res.With(logined)
	}

	// 3. 准备事务.
	o.userService = services.NewUsersService(sess)
	o.userStaticService = services.NewUserStatisticService(sess)

	// 3.1 事务提交.
	if err = db.TransactionWithSession(ctx, sess,
		o.RunMobile,
		o.RunUser,
		o.RunSync,
	); err != nil {
		return res.WithError(err)
	}

	// 4. 执行登录.
	if logined, err = o.InitLoginedForUser(ctx, o.oauth, o.request.Device); err != nil {
		return res.WithError(err)
	}

	// 5. 返回结果.
	return res.With(logined)
}

// RunMobile
// 检查手机.
func (o *Logic) RunMobile(ctx context.Context, _ *db.Session) (err error) {
	// 1. 号码存在.
	if o.userMobile != nil {
		return
	}

	// 2. 创建号码.
	if o.userMobile, err = o.userMobileService.Dao.AddByStruct(ctx, &models.UserMobiles{
		Mobile: o.oauth.OpenMobile,
		UserId: o.oauth.UserId,
	}); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// RunUser
// 创建账号.
func (o *Logic) RunUser(ctx context.Context, _ *db.Session) (err error) {
	var has bool

	// 1. 准备账号.
	reg := &models.Users{
		State:    kind.UserStateNormal,
		Nickname: o.request.Nickname,
		Mobile:   kind.Mobile(o.userMobile.Mobile.Mask()),
	}

	// 2. 检查昵称.
	if _, has, err = o.userService.Dao.GetBy(ctx, "nickname", o.request.Nickname); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 3. 调整昵称.
	//    若昵称存在则在原昵称后面加上一段数值.
	if has {
		reg.Nickname = fmt.Sprintf(`%s%d`, reg.Nickname, o.oauth.Id)
	}

	// 4. 创建账号.
	if o.user, err = o.userService.Dao.AddByStruct(ctx, reg); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 5. 账号统计.
	if _, err = o.userStaticService.Dao.AddByStruct(ctx, &models.UserStatistic{
		UserId: o.user.Id,
	}); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// RunSync
// 同步用户.
//
// 将相关表的数据同步用户ID, 建立关联.
func (o *Logic) RunSync(ctx context.Context, _ *db.Session) (err error) {
	// 1. 同步授权.
	//    将授权的用户ID关系建立.
	if _, err = o.oauthService.Dao.UpdateFieldsById(ctx, map[string]any{
		"user_id": o.user.Id,
	}, o.oauth.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else {
		o.oauth.UserId = o.user.Id
	}

	// 2. 同步手机.
	//    将手机号的用户关系建立.
	if _, err = o.userMobileService.Dao.UpdateFieldsById(ctx, map[string]any{
		"user_id": o.user.Id,
	}, o.userMobile.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else {
		o.userMobile.UserId = o.user.Id
	}
	return
}
